package cn.weekdragon.gscore.adapter.model.message;

import lombok.Data;
import java.util.ArrayList;
import java.util.List;

@Data
public class MessageChain extends Message{

    protected List<Message> messageChain;

    private transient String stringContent;

    public String contentToString(){
        if(stringContent != null){
            return stringContent;
        }
        if(messageChain == null || messageChain.isEmpty()){
            stringContent = "";
        }else{
            StringBuilder sb = new StringBuilder();
            for (Message message : messageChain) {
                if(message instanceof Plain){
                    sb.append(((Plain) message).getText());
                }
            }
            stringContent = sb.toString().trim();
        }
        return stringContent;
    }

    @Override
    public MessageChain plus(Message message) {
        if(messageChain == null){
            messageChain = new ArrayList<>();
        }
        messageChain.add(message);
        return this;
    }

    @Override
    public MessageChain plus(String message) {
        if(messageChain == null){
            messageChain = new ArrayList<>();
        }
        messageChain.add(new Plain(message));
        return this;
    }

    @Override
    public List<Message> toList() {
        if(messageChain == null){
            return super.toList();
        }
        return messageChain;
    }

    public boolean isEmpty(){
        return toList().isEmpty();
    }

    public Source getSource(){
        for (Message message : toList()) {
            if(message instanceof Source){
                return (Source) message;
            }
        }
        return null;
    }
}
